package com.webex.ta.hydra.gui.action;

import com.webex.ta.hydra.gui.table.HydraTable;
import com.webex.ta.hydra.gui.GuiPackage;
import com.webex.ta.hydra.gui.HydraIdeFrame;
import com.webex.ta.hydra.clipboard.ClipBoard;
import com.webex.ta.hydra.core.Command;
import com.webex.ta.hydra.Constants;

import javax.swing.*;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.awt.event.ActionEvent;

/**
 * Author: Vegaz
 * Date: 2010-10-28
 * Time: 11:16:53
 */
public class PasteCellAction implements ActionHandler {
    private static Set<String> commands = new HashSet<String>();

    static {
        commands.add(ActionNames.PASTE);
    }

    public Set<String> getActionNames() {
        return commands;
    }

    public void doAction(ActionEvent e) {
        HydraIdeFrame frame = GuiPackage.getInstance().getIdeFrame();
        HydraTable table = GuiPackage.getInstance().getHydraTable();
        List<List<String>> cellValues = ClipBoard.getInstance().getCellValues();
        if (cellValues == null || cellValues.size() == 0) return;

        if (table.getSelectedRow() < 0) {
            JOptionPane.showConfirmDialog(frame, "Please select ONE cell to paste the cell values", "Error",
                    JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE);
            return;
        } if (table.getSelectedColumnCount() > 1 || table.getSelectedRowCount() > 1) {
            JOptionPane.showConfirmDialog(frame, "Please select ONE cell to paste the cell values", "Error",
                    JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE);
            return;
        }

        int startRow = table.getSelectedRow();
        int startCol = table.getSelectedColumn();

        int lastRow = Math.min(startRow + cellValues.size(), table.getRowCount());
        int i = 0;
        for (int row = startRow; row < lastRow; row++, i++) {
            Command cmd = table.getModel().getCommandAt(row);
            Command newCommand = cmd.clone();
            List<String> columnValues = cellValues.get(i);
            int j = startCol;
            for (String val : columnValues) {
                switch (j) {
                    case Constants.COLUMN_BREAKPOINT:
                        break;
                    case Constants.COLUMN_KEYWORD:
                        newCommand.setKeyword(val);
                        break;
                    default:
                        newCommand.setParameter(j - 2, val);
                }
                j++;
            }
            table.getModel().updateCommand(cmd, newCommand);
        }
        table.repaint();
    }

}
